package home.study.xxy.bs.fifter;

import home.study.xxy.bs.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @title: UserInterceptor
 * @功能:  自定义拦截器 用户token校验
 * @Author Xiao Xiangyu
 * @Date: 2021/5/1 13:39
 * @Version 1.0
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//
//        // 指定前端的请求域名
//        String allowDomain = "http://localhost";
//        String originHeads = request.getHeader("Origin");
//        if(allowDomain.equals(originHeads)){
//            //设置允许跨域的配置
//            // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
//            response.setHeader("Access-Control-Allow-Origin", originHeads);
//        }
//
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//
//        response.setHeader("Access-Control-Allow-Headers",
//                "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
//
//        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//
//        response.setHeader("X-Powered-By", "Jetty");
//
//        String method = request.getMethod();
//        if (method.equals("OPTIONS")) {
//
//            response.setStatus(200);
//
//            return false;
//        }
//        return true;
//    }

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//支持跨域请求
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept,Access-Token");
        response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS,PATCH");
        response.setHeader("Access-Control-Allow-Credentials","true");//是否支持cookie跨域
        HttpSession session = request.getSession(false);
//        if (session.getAttribute("userId")!=null){
//
//            return true;
//        }else{
//            response.setStatus(401);
//            return false;
//        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
